<template>
    <div>
        <basic-container>
            <div class="app-container">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
                    <el-form-item label="机种名称">
                        <el-input v-model="queryParams.aircraft" placeholder="请输入设备名称" clearable @clear="getList" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini"
                            @click="handleAdd">新增机种</el-button>
                    </el-col>
                </el-row>
                <el-table v-loading="loading" :data="menuList" :default-expand-all="isExpandAll"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" @expand-change="addChange">
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <div style="display: flex;margin: 0 0 30px 0;">
                                <div style="margin: 10px 10px 0 0;color: red;"> * 工艺参数</div>
                                <div>
                                    <el-select v-model="queryParams.ft_id" placeholder="请选择"
                                        @change="valueChang(scope.row)">
                                        <el-option v-for="item in scope.row.allows" :key="item.key" :label="item.value"
                                            :value="item.key">
                                        </el-option>
                                    </el-select>
                                </div>
                            </div>
                            <el-table :data="craftsList" style="width: 200%">
                                <el-table-column prop="facility_name" label="设备名称">
                                </el-table-column>
                                <el-table-column prop="describe" label="iO点描述" align="center">
                                </el-table-column>
                                <el-table-column prop="address" label="PLC地址" align="center">
                                </el-table-column>
                                <el-table-column prop="types" label="PLC数据类型" align="center">
                                </el-table-column>
                                <el-table-column prop="write" label="当前设定值" align="center">
                                    <template slot-scope="scope">
                                        <el-select v-model="scope.row.write"  placeholder="请选择"
                                            v-if="scope.row.types == 'Bool'" @change="handleBlur(scope, scope.$index)">
                                            <el-option v-for="item in optionsBool" :key="item.value" :label="item.label"
                                                :value="item.value">
                                            </el-option>
                                        </el-select>
                                        <el-input v-else  :type="scope.row.types == 'String' ? '' : 'number'"
                                            v-model="scope.row.write"
                                            @blur="handleBlur(scope, scope.$index)"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </template>
                    </el-table-column>
                    <el-table-column prop="aircraft" label="机种名称"></el-table-column>
                    <el-table-column prop="route_name" label="工艺路径" align="center"></el-table-column>
                    <el-table-column prop="in_production" label="是否生产中" align="center">
                        <template slot-scope="scope">{{ scope.row.in_production ? '是' : '否' }}</template>
                    </el-table-column>
                    <el-table-column prop="specification" label="机种规格" align="center"></el-table-column>
                    <el-table-column prop="time" label="产品添加时间" align="center"></el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit"
                                @click="handleUpdate(scope.row)">修改</el-button>
                            <!-- <el-button :disabled="!scope.row.in_production" :loading="isLoading(scope.row)" size="mini"
                                type="text" icon="el-icon-magic-stick" @click="startUp(scope.row)">下发配方</el-button> -->
                            <el-button size="mini" type="text" icon="el-icon-delete"
                                @click="handleDelete(scope.row, 1)">
                                删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" :total="total" :page.sync="queryParams.index"
                    :limit.sync="queryParams.size" @pagination="getList" />
                <!-- 添加或修改菜单对话框 -->
                <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body
                    :close-on-click-modal="false">
                    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                        <el-row>
                            <el-col :span="19">
                                <el-form-item label="机种名称" prop="aircraft">
                                    <el-input v-model="form.aircraft" placeholder="请输入机种名称" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="产品规格" prop="specification">
                                    <el-input v-model="form.specification" placeholder="请输入产品规格" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="对应路径" prop="route_id">
                                    <el-select v-model="form.route_id" placeholder="请选择" style="width: 100%;">
                                        <el-option v-for="item in pathList" :key="item.key" :label="item.value"
                                            :value="item.key">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </el-dialog>
            </div>
            <el-dialog :title="titleTwo" :visible.sync="openTwo" width="780px" append-to-body
                :close-on-click-modal="false">
                <el-form ref="form" :model="formTwo" :rules="rules" label-width="180px">
                    <el-row>
                        <el-col :span="19">
                            <el-form-item label="PLC数据变量" prop="types">
                                <el-select v-model="formTwo.types" placeholder="请选择" style="width: 100%;"
                                    @change="chengValue">
                                    <el-option v-for="item in datatypeMapping" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="19">
                            <el-form-item label="选择设备" prop="facility_id">
                                <el-select v-model="formTwo.facility_id" placeholder="请选择" style="width: 100%;"
                                    @change="chengValue">
                                    <el-option v-for="item in unitType" :key="item.key" :label="item.value"
                                        :value="item.key">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="19">
                            <el-form-item label="PLC地址" prop="address">
                                <el-input v-model="formTwo.address" placeholder="请输入PLC地址" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="19">
                            <el-form-item label="PLC变量备注" prop="describe">
                                <el-input v-model="formTwo.describe" placeholder="请输入PLC变量备注" />
                            </el-form-item>
                        </el-col>
                        <div>
                            <el-col :span="19">
                                <el-form-item label="设备参数写入值" prop="write">
                                    <el-input v-model="formTwo.write" placeholder="请输入PLC上限" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="PLC上限" prop="upper">
                                    <el-input v-model="formTwo.upper" placeholder="请输入PLC上限" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="19">
                                <el-form-item label="PLC下限" prop="floor">
                                    <el-input v-model="formTwo.floor" placeholder="请输入PLC下限" />
                                </el-form-item>
                            </el-col>
                        </div>
                        <el-col :span="19">
                            <el-form-item label="是否启用上下限数据限制" prop="compare">
                                <el-select v-model="formTwo.compare" placeholder="请选择" style="width: 100%;">
                                    <el-option v-for="item in options" :key="item.value" :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="addunitType">确 定</el-button>
                    <el-button @click="cancelType">取 消</el-button>
                </div>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import {
    getfacilitylist,
    eidParm,
    addaircraft,
    eidaircraft,
    dleaircraft,
    addCraft,
    aircraftStart,
    AircraftList,
    ftidList
} from "@/api/craft";

import { mapGetters } from "vuex";

export default {
    data() {
        return {
            titleTwo: '',
            currentRowIndex: null,
            openTwo: false,
            parameter: [],
            optionsBool: [
                {
                    id: 1,
                    value: 'False',
                    label: 'False'
                }, {
                    id: 2,
                    value: 'True',
                    label: 'True'
                },
                {
                    id: 3,
                    value: '',
                    label: '不选'
                }
            ],

            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            value1: [],
            total: 1,
            unitType: [],
            inMess: [],
            menuList: [],
            roleOptions: [],
            dataMuen: [
                {
                    value: 0,
                    label: "是",
                },
                {
                    value: 1,
                    label: "否",
                },
            ],
            options: [{
                value: '1',
                label: '是'
            }, {
                value: '0',
                label: '否'
            }],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否展开，默认全部折叠
            isExpandAll: false,
            // 重新渲染表格状态
            refreshTable: true,
            // 查询参数
            queryParams: {
                aircraft: null,
                index: 1,
                size: 10,
                ft_id: null,
            },
            datatypeMapping: [
                { value: "Bool", label: "布尔类型" },
                { value: "Float", label: "浮点型" },
                { value: "Int", label: "整数32位" },
                { value: "Short", label: "整数16位" },
                { value: "String", label: "字符串类型" },
            ],
            pathList: [],
            craftsList: [],
            // 表单参数
            form: {},
            formTwo: {},
            // 表单校验
            rules: {
                aircraft: [
                    { required: true, message: "设备名称不能为空", trigger: "blur" },
                ],
                serials: [
                    { required: true, message: "设备编号不能为空", trigger: "blur" },
                ],
                station: [
                    { required: true, message: "设备工站不能为空", trigger: "blur" },
                ],
                workplace: [
                    { required: true, message: "设备地址不能为空", trigger: "blur" },
                ],
                time: [
                    { required: true, message: "设备添购时间不能为空", trigger: "blur" },
                ],
                expired: [
                    { required: true, message: "设备有效日期不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {
        this.getList();
        this.coefficient();
        // this.startPolling()
    },
    computed: {
        ...mapGetters(["userInfo", "menu"]),
    },
    beforeDestroy() {

        // 在组件销毁时清除定时器，防止内存泄漏
        clearInterval(this.timer);

    },
    methods: {

        isLoading(row) {
            // 检查当前行是否是当前正在加载的行  
            return this.currentRowIndex === row.index;
        },
        addChange() {
            this.queryParams.ft_id = null
            this.craftsList = []
        },
        onPhoneInput(event) {
            let value = event;
            // 使用正则表达式过滤非数字字符
            value = value.replace(/\D/g, "");
            // 更新输入框的值
            this.form.phone = value;
        },
        chengValue() {
            console.log(this.formTwo);
        },
        /** 查询菜单列表 */
        getList() {
            this.loading = true;
            getfacilitylist(this.queryParams).then((response) => {
                this.menuList = response.data.data;
                this.total = response.data.total;
                this.loading = false;
            });
        },
        handleBlur(row) {
            console.log(row)
            let dataFarm = {
                craft_id: row.row.craft_id,
                upper: row.row.upper,
                floor: row.row.floor,
                write: row.row.write,
                compare: row.row.compare
            }
            eidParm(dataFarm).then(res => {
                console.log(res);
            })
        },
        upFormula(row) {

            this.openTwo = true;
            this.resetFormtwo();
            this.titleTwo = "新增工艺";
            this.unitType = row.allows
            this.formTwo.aircraft_id = row.aircraft_id
        },

        cancel() {
            this.open = false;
            this.getList();
            this.reset();
        },
        startUp(row) {
            this.currentRowIndex = row.index;
            let airId = {
                aircraft_id: row.aircraft_id
            }
            aircraftStart(airId).then(res => {
                this.currentRowIndex = null;
                this.$message({
                    message: res.data.msg,
                    type: "success",
                });
            }).catch(err => {
                console.log(err);
                this.currentRowIndex = null;
            })
        },
        cancelType() {
            this.openTwo = false;
            this.getList();
            this.resetFormtwo();
        },
        resetFormtwo() {
            this.formTwo = {
                facility_id: null,
                aircraft_id: null,
                address: null,
                types: null,
                describe: null,
                upper: null,
                floor: null,
                compare: null,
                write: null,
            };
        },
        addunitType() {
            this.formTwo.upper = this.formTwo.types == 'Bool' ? null : this.formTwo.types == 'String' ? null : this.formTwo.upper
            this.formTwo.floor = this.formTwo.types == 'Bool' ? null : this.formTwo.types == 'String' ? null : this.formTwo.floor
            this.formTwo.write = this.formTwo.types == 'Bool' ? null : this.formTwo.types == 'String' ? null : this.formTwo.write
            this.formTwo.compare = this.formTwo.types == 'Bool' ? 0 : this.formTwo.types == 'String' ? 0 : this.formTwo.compare
            addCraft(this.formTwo).then(() => {
                this.$message({
                    message: "添加成功",
                    type: "success",
                });
                this.openTwo = false;
                this.getList();
                this.resetFormtwo();
            });
        },
        // 表单重置
        reset() {
            this.form = {
                aircraft: null,
                specification: null,
                route_id: null,
            };
        },
        coefficient() {
            AircraftList().then(res => {

                this.pathList = res.data.data
            })
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                index: 1,
                size: 10,
                aircraft: null,
            };
            this.getList();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.open = true;
            this.reset();
            this.title = "新增机种";
        },

        /** 修改按钮操作 */
        handleUpdate(row) {
            console.log(row);
            this.reset();
            this.form = row;
            this.open = true;
            this.title = "修改设备";
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.title == "新增机种") {
                        addaircraft(this.form).then(() => {
                            this.$message({
                                message: "添加成功",
                                type: "success",
                            });
                            this.open = false;
                            this.getList();
                            this.reset();
                        });
                    } else {
                        eidaircraft(this.form).then(() => {
                            this.$message({
                                message: "修改成功",
                                type: "success",
                            });
                            this.open = false;
                            this.getList();
                            this.reset();
                        });
                    }
                }
            });
        },
        valueChang(row) {
            this.fetchData(row);

        },
        fetchData(row) {
            let query = {
                ft_id: this.queryParams.ft_id,
                aircraft_id: row.aircraft_id
            };
            ftidList(query).then(res => {

                this.craftsList = res.data.data;
            }).catch(error => {
                console.error("Error fetching data:", error);
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {

            this.$confirm('是否确认删除名称为"' + row.aircraft + '"的机种？')
                .then(() => {
                    let queyId = {
                        aircraft_id: row.aircraft_id
                    }
                    dleaircraft(queyId).then(() => {
                        this.$message({
                            message: "删除成功",
                            type: "success",
                        });
                        this.open = false;
                        this.getList();
                        this.reset();
                    });
                })
                .catch(() => { });
        },
    },
};
</script>
